from django.db import transaction
from rest_framework import serializers

from goods.models import SKUImage, SKU, SPUSpecification, SPU, SpecificationOption, SKUSpecification


class SkusImagesSerializer(serializers.ModelSerializer):
    sku_id = serializers.IntegerField(label='sku商品id')
    sku = serializers.StringRelatedField(label='sku商品名称', read_only=True)

    class Meta:
        model = SKUImage
        fields = ('   id', 'sku', 'sku_id', 'image')
        extra_kwargs = {
            'id': {'read_only': True}
        }
        ordering = ('sku_id',)

    def validate_sku_id(self, value):
        try:
            sku = SKU.objects.get(id=value)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('商品不存在')

        return value

    def create(self, validated_data):
        sku_image = super().create(validated_data)
        sku = SKU.objects.get(id=validated_data['sku_id'])
        if not sku.default_image:
            sku.default_image = sku_image.image
            sku.save()

        return sku_image


class SkusSimpleSerializer(serializers.ModelSerializer):
    class Meta:
        model = SKU
        fields = ('id', 'name')


class SpecsSerializer(serializers.ModelSerializer):
    spec_id = serializers.IntegerField(label='规格id')
    option_id = serializers.IntegerField(label='选项id')

    class Meta:
        model = SPUSpecification
        fields = ('spec_id', 'option_id')


class SkusSerializer(serializers.ModelSerializer):
    spu_id = serializers.IntegerField(label='商品SPU ID')
    category = serializers.StringRelatedField(label='三级分类名称', read_only=True)
    specs = SpecsSerializer(label='商品规格信息', many=True)

    class Meta:
        model = SKU
        exclude = ('default_image', 'create_time', 'update_time', 'spu', 'comments')
        extra_kwargs = {
            'id': {'read_only': True},
            'sales': {'read_only': True}
        }

    def validate(self, attrs):
        try:
            spu = SPU.objects.get(id=attrs['spu_id'])
        except SPU.DoesNotExist:
            raise serializers.ValidationError('商品不存在')

        attrs['category_id'] = spu.category3.id

        specs = attrs['specs']
        spu_specs = spu.specs.all()
        spu_counts = spu_specs.count()

        if spu_counts != len(specs):
            raise serializers.ValidationError('规格数量有误')

        specs_ids = [spec.get('spec_id') for spec in specs]
        spu_specs_ids = [spec.id for spec in spu_specs]

        specs_ids.sort()
        spu_specs_ids.sort()

        if spu_specs_ids != specs_ids:
            raise serializers.ValidationError('规格参数有误')

        for spec in specs:
            spec_id = spec['spec_id']
            option_id = spec['option_id']

            options = SpecificationOption.objects.filter(spec_id=spec_id)
            option_ids = [option.id for option in options]
            if option_id not in option_ids:
                raise serializers.ValidationError('选项参数有误')

        return attrs

    def create(self, validated_data):
        specs = validated_data.pop('specs')

        with transaction.atomic():
            sku = SKU.objects.create(**validated_data)

            for spec in specs:
                SKUSpecification.objects.create(
                    sku=sku,
                    spec_id=spec['spec_id'],
                    option_id=spec['option_id']
                )
        return sku

    def update(self, instance, validated_data):
        specs = validated_data.pop('specs')

        with transaction.atomic():
            sku = SKU.objects.create(**validated_data)
            instance.specs.all().delete()

            for spec in specs:
                SKUSpecification.objects.create(
                    sku=instance,
                    spec_id=spec['spec_id'],
                    option_id=spec['option_id']
                )
        return sku
